<div class="table-controls">
  Show
  <select id="display_count">
    <option value="10" selected="selected">10</option>
    <option value="20">20</option>
    <option value="50">50</option>
    <option value="100">100</option>
  </select>
  entries

  <ul class="pagination">

  </ul>
</div>
<table class="manual-table">
  <thead>
    <tr>
      <?php foreach($tableColumns as $tableColumn): ?>
      <th><?php echo $tableColumn['label'] ?></th>
      <?php endforeach; ?>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td colspan="<?php echo count($tableColumns)+1 ?>">Loading...</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <?php foreach($tableColumns as $tableColumn): ?>
      <th><?php echo $tableColumn['label'] ?></th>
      <?php endforeach; ?>
      <th>Actions</th>
    </tr>
  </tfoot>
</table>
<br /><br /><br />

<script type="text/javascript">

    var oTable;
    var aoColumns= <?php echo DataTables::renderAOColumns($tableColumns); ?>;
    var sAjaxSource = '<?php echo url_for('user/ajaxdata') ?>';

    function toggleLoading()
    {
        setTimeout(function(){
            $(".loading-notification").toggle();
        }, 500);
    }

    getActionButtons = function(id) {
      var actionButtons = '<ul class="actions">';
      actionButtons += '<li><a class="view tooltip record-view nyroModal" href="<?php echo url_for('user/history') ?>?id='+id+'" title="View Account History">view</a></li>';
      actionButtons += '<li><a class="edit tooltip record-edit" href="#" title="Edit Item">edit</a></li>';
      actionButtons += '<li><a class="delete tooltip record-delete nyroModal" href="#delete_box" title="Delete Item">delete</a></li>';
      actionButtons += '</ul>';
      return actionButtons;
    }

    getPaginationButtons = function(limit, total, current) {
      var buttonsBeforeCurrent = 2;
      var buttonsAfterCurrent = 2;
      var totalPages = Math.ceil(total/limit);
      var prevPage = (current != 1) ? parseInt(current)-1 : current;
      var nextPage = (current != totalPages) ? parseInt(current)+1 : current;
      var paginationButtons = '<li><a id="first_page" data-page="'+'1'+'" class="button blue" href="javascript:void(0)">&laquo; first</a></li>';
      paginationButtons += '<li><a id="prev_page" data-page="'+prevPage+'" class="button blue" href="javascript:void(0)">&lt; prev</a></li>';
      paginationButtons += '<li class="hellip">&#133;</li>';
      for(i = parseInt(current)-buttonsBeforeCurrent; i <= parseInt(current)+buttonsAfterCurrent; i++ ) {
        if(i > 0 && i <= parseInt(totalPages)) {
          var buttonClass = (i == current || (i == 1 && current == 0)) ? 'gray' : 'blue';
          paginationButtons += '<li><a data-page="'+i+'" class="page-button button '+buttonClass+'" href="javascript:void(0)">'+i+'</a></li>';
        }
      }
      paginationButtons += '<li class="hellip">&#133;</li>';
      paginationButtons += '<li><a id="next_page" data-page="'+nextPage+'" class="button blue" href="javascript:void(0)">&gt; next</a></li>';
      paginationButtons += '<li><a id="last_page" data-page="'+totalPages+'" class="button blue" href="javascript:void(0)">&raquo; last</a></li>';
      return paginationButtons;
    }

    tableReload = function(limit, page) {

      if(page == undefined) {
        page = 1;
      }
      if(limit == undefined) {
        limit = 10;
      }

      params = {
        iDisplayLength: limit,
        iDisplayStart: ((parseInt(page)-1)*limit),
        'param[status]' : $('#status').val()
      }

      if($('#first_name').val() != '') {
        params["param[first_name]"] = $('#first_name').val()
      }
      if($('#last_name').val() != '') {
        params["param[last_name]"] = $('#last_name').val()
      }


      $.ajax({
        url: sAjaxSource,
        data: params,
        beforeSend: function() {
          $('.manual-table tbody').empty();
        },
        success: function(response) {
          if(parseInt(response.iTotalRecords) > 0) {

            $('.pagination').html(getPaginationButtons(limit,response.iTotalRecords,page));

            $.each(response.aaData, function(rowindex, row) {
              var recordID = row[0];
              var rowText = '<tr>';
              $.each(row, function(valueindex, value) {
                  var tdText = '<td>'+value+'</td>';
                  rowText += tdText;
              });
              rowText += '<td>'+getActionButtons(recordID)+'</td>';
              rowText += '</tr>';

              $('.manual-table tbody').append(rowText);
            });
          }
          else {
            $('.manual-table tbody').html('<tr><td colspan="<?php echo count($tableColumns)+1 ?>">No data found.</td></tr>');
          }
        }
      });
    }


    $(document).ready(function(event) {

        tableReload();


        // set current row ID as selectedId when clicking a link inside
        $('.manual-table tbody tr td a').live('click',function() {
          var selectedTR = $(this).parents('tr');
          selectedID = selectedTR.children('td:eq(0)').text();
        });


        // Filter
        $('#filter_button').click(function() {
          tableReload($('#display_count').val());
        });

        // delete record
        $('#yes_delete').click(function() {
          $.ajax({
            url: '<?php echo url_for('user/ajaxDelete') ?>',
            data: {id: selectedID },
            method: 'POST',
            beforeSend: function() {
              toggleLoading();
            },
            success: function(response) {
              $.nmTop().close();

              tableReload();
              toggleLoading();
            }
          });
        });

        $('#no_delete').click(function() {
          $.nmTop().close();
        });

        // edit record
        $('.record-edit').live('click',function() {
          editing = true;
          $('#crud_new').click();
          $.ajax({
	            url: '<?php echo url_for("user/ajaxFormEdit") ?>',
	            type: 'POST',
	            data: {id: selectedID },
	            dataType: 'html',
              beforeSend: function() {
                toggleLoading();
              },
	            success: function(response) {
                  $("#tab2-content").empty();
	                $("#tab2-content").html(response);
	                toggleLoading();
	            }
	        });
        });

        // view record
        $('.record-view').live('click',function() {

        });

        // change number of displayed entries
        $('#display_count').change(function() {
          tableReload($(this).val());
        });

        // event handler for pagination buttons
        $('.pagination li a').live('click',function() {
          var targetPage = $(this).attr('data-page');
          if(targetPage >= 0 && targetPage != $('.page-button.gray').attr('data-page')) {
            tableReload($('#display_count').val(),targetPage);
          }
        });

        toggleLoading();

    });
</script>